new Vue({
    el: '#app',
    data: {
        isDetail: false, //是否显示交易详情
        isShade:false,//是否显示遮罩层
        isPayment: false, //是否显示付款详情
        isWxMoney: true, //是否显示微信支付后面的对号
        isPaymentOne: true, //是否自动判断支付方式
        oilCardIndex: null, //显示哪一个油卡后面的对号
        isOilDetail: false, //是否显示支付后的付款详情
        isOfPayment: false, //是否需要默认油卡
        isFavourable: false, //是否显示优惠券列表
        isShopList: false, //是否显示便利店
        isOffset: false, //是否采用积分抵现
        classifyScroll: [], //便利店滚动左边
        goodsScroll: '', //便利店滚动右边
        goodsScrollY: '', //便利店当前滚动的高度
        goodsTitle: '', //便利店顶部的分类名称
        paymentNew: '微信支付',//显示的支付方式
        favourableListNew: '', //当前优惠券的数目显示
        paymentMoney: 0, //当前选中或者默认选中的油卡金额
        numSum: 0, //商品数量
        oilName: '',//油品名称
        oilMoneyNum: 0, //油品价格
        shopMoneyNum: 0, //非油品价格
        favourMoneyNum: 0,//优惠券价格
        bpMonyeNum: 0, //积分抵现价格
        oilAdvan: 0,//油枪优惠
        timeAdvan: 0,//分时优惠
        oilL: 0,//升
        orderList: [], //详情页里面，非油品列表
        oilCardList: [], //油卡支付的油卡列表
        oilFavourableList: [], //优惠券列表
        shopList: [], //便利店商品列表
        listHeight: [], //便利店商品列表高度
        shophostList: [],//便利店热门商品
        balls: [{ show: false }, { show: false }, { show: false }],//小球个数
        dropBalls: [], //存放小球
        NumX: 0,//小球X坐标
        NumY: 0,//小球Y坐标
        integ: 0,//积分
        integMoney: 0, //抵现金额
        isShopsStart:true, //初始化
        goodsLists:[], //左边列表
        isLoading:false, //支付中样式
        isSucceed:false //支付成功
    },
    created() {
        this.oilCard()
        this.oilFavourable()
        this.goods()
    },
    mounted() {
        this.$nextTick(function () {
            this.shopHotHeight()
            this.bScroll()
            //请求初始化数据
            axios.get('data/card.json')
                .then(response => {
                    this.numSum = response.data.data.oil.numsum
                    this.oilMoneyNum = response.data.data.oil.oilMoney
                    this.oilAdvan = response.data.data.oil.oilAdvan
                    this.timeAdvan = response.data.data.oil.timeAdvan
                    this.oilL = response.data.data.oil.oilL
                    this.oilName = response.data.data.oil.oilName
                    this.integ = response.data.data.oil.integ
                    this.integMoney = response.data.data.oil.integMoney
                })
                .catch(function (error) {
                    console.log(error);
                });
            //获取小球位置
            this.NumX = this.$refs.positionNum.getBoundingClientRect().left
            this.NumY = window.innerHeight - this.$refs.positionNum.getBoundingClientRect().top
            // this.shopScroll()
        })
    },
    beforeUpdate() {
        // 执行
        this.$nextTick(function () {
            this.fastclick()
        })
    },
    // 计算属性
    computed: {
        totalMoneyFiexd() {
            return this.totalMoney.toFixed(2)
        },
        //总金额
        totalMoney() {
            return this.oilMoneyNum + this.shopMoneyNum + this.sumAdvan
        },
        //总优惠
        sumAdvan() {
            return -(this.bpMonyeNum + this.oilAdvan + this.timeAdvan + this.favourMoneyNum).toFixed(2)
        },
        //当前的index
        activeIndex() {
            for (let i = 0; i < this.listHeight.length; i++) {
                let heightI = this.listHeight[i]
                let heightJ = this.listHeight[i + 1]
                if (!heightJ || this.goodsScrollY < heightJ && this.goodsScrollY >= heightI) {
                    this.goodsTitle = this.shopList[i].name

                    return i
                }
            }
        }
    },
    methods: {
        //初始化油卡
        oilCard() {
            axios.get('data/card.json')
                .then(response => {
                    this.oilCardList = response.data.data.cardList
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
        //初始化优惠券
        oilFavourable() {
            axios.get('data/card.json')
                .then(response => {
                    this.oilFavourableList = response.data.data.favourableList
                    this.favourableListNew = this.oilFavourableList.length + '张优惠券可用'
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
        //便利店初始化数据
        goods() {
            axios.get('data/list.json')
                .then(response => {
                    this.shopList = response.data.data
                    console.log(this.shopList.length)
                    this.goodsTitle = this.shopList[0].name
                    //增加num,并取出所有数据
                    let shopArr = []
                    this.shopList.forEach(item => {
                        if (item.goods.length > 0) {
                            item.goods.forEach(items => {
                                this.$set(items, 'num', 0)
                                shopArr.push(items)
                            })
                        }
                    })
                    //数据按照销量排行
                    this.shophostList = shopArr.sort(this.sortArr('sales'))
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
        //根据销量对数组进行排序
        sortArr(property) {
            return function (a, b) {
                let num1 = a[property]
                let num2 = b[property]
                return num2 - num1
            }
        },
        // 判断是否允许用户使用
        oilMoney() {
            this.oilCardList.forEach((obj, index) => {
                if (obj.isSupport) {
                    this.$set(this.oilCardList[index], 'isMoney', true)
                } else {
                    // 
                    if (this.totalMoneyFiexd > obj.money) {
                        this.$set(this.oilCardList[index], 'isMoney', true)
                    } else {
                        this.$set(this.oilCardList[index], 'isMoney', false)
                    }
                    // 
                }
            });
        },
        // 判断当前的加油卡为哪一张
        oilNewOn() {
            /*  */
            let arr = []
            //判断是否需要默认
            if (this.isOfPayment) {
                this.isPaymentOne = (this.totalMoneyFiexd > this.paymentMoney) ? true : false
                //把能用的油卡都放起来
                this.oilCardList.forEach(element => {
                    if (!element.isMoney) {
                        arr.push(element.money)
                    }
                });
                //如果油余额不足就使用微信支付
                let max = Math.max.apply(null, arr)
                if (this.totalMoneyFiexd > max) {
                    this.clickOilWx()
                    this.isOfPayment = false
                    this.isPaymentOne = true
                    console.log('我觉得我应该走微信支付')
                }
            }
            //初始化的时候采用油卡支付
            if (this.isPaymentOne) {
                this.isPaymentOne = false
                this.isOfPayment = true
                for (i in this.oilCardList) {
                    if (!this.oilCardList[i].isMoney) {
                        this.paymentNew = this.oilCardList[i].name
                        this.paymentMoney = this.oilCardList[i].money
                        this.isWxMoney = false
                        this.oilCardIndex = i
                        break;
                    }
                }
            }
        },
        //计算热门数据的高度
        shopHotHeight() {
            const htmlHeight = document.documentElement.clientHeight
            const headerHeight = this.$refs.header.offsetHeight
            const shopTitHeight = this.$refs.shopTit.offsetHeight
            const footerHeight = this.$refs.footer.offsetHeight
            const discountHeight = this.$refs.discount.offsetHeight
            const height = htmlHeight - headerHeight - shopTitHeight - footerHeight - discountHeight
            this.$refs.wrapper.style.height = height + 'px'
        },
        //加载滚动
        bScroll() {
            const scroll = new BScroll(this.$refs.wrapper, {
                click: true
            })
        },
        //点击微信支付
        clickOilWx() {
            this.isWxMoney = true
            this.oilCardIndex = null
            this.isOilDetail = false
            this.paymentNew = '微信支付'
            this.isOfPayment = false
        },
        //点击油卡
        clickOilList(index, isMoney, name, money) {
            if (!isMoney) {
                this.oilCardIndex = index
                this.isWxMoney = false
                this.isOilDetail = false
                this.paymentNew = name
                this.paymentMoney = money
                this.isOfPayment = true
            }
        },
        //点击优惠券列表
        clickFavourableList(name, money) {
            this.favourableListNew = name + `(￥${money} )x1`
            this.favourMoneyNum = money
            this.clickFavourable(false)
        },
        //点击下次再用
        noFavour() {
            this.favourableListNew = "下次再用"
            this.favourMoneyNum = 0
            this.clickFavourable(false)
        },
        //添加商品
        shopAdd(el, num, cateId, goodsId) {
            this.drop(el.target)
            if (num == 0) {
                //
                let index = this.shophostList.findIndex(item => {
                    return item.goods_id == goodsId
                })
                this.shophostList[index].num++
                this.numSum++
                this.shopMoneyNum += (+this.shophostList[index].price)
            } else {
                //
                let lists = this.shopList.find(item => {
                    return item.cateid == cateId
                })
                let index = this.shopList.indexOf(lists)
                let indexs = lists.goods.findIndex(item => {
                    return item.goods_id == goodsId
                })
                let arrNew = this.shopList[index].goods[indexs]
                arrNew.num++
                this.numSum++
                this.shopMoneyNum += (+arrNew.price)
            }
            this.getShopCard()
        },
        //改变购物车
        getShopCard() {
            this.orderList = []
            this.shophostList.forEach((item, index) => {
                if (item.num > 0) {
                    this.orderList.push(this.shophostList[index])
                }
            })
        },
        // 增加
        shopOrderAdd(index) {
            this.numSum++
            this.orderList[index].num++
            this.shopMoneyNum += (+this.orderList[index].price)
        },
        //减少商品
        shopMinus(num, cateId, goodsId) {
            if (num == 0) {
                let index = this.shophostList.findIndex(item => {
                    return item.goods_id == goodsId
                })
                if (this.shophostList[index].num > 0) {
                    this.shophostList[index].num--
                    this.numSum--
                    this.shopMoneyNum -= (+this.shophostList[index].price)
                }
            } else {
                let lists = this.shopList.find(item => {
                    return item.cateid == cateId
                })
                let index = this.shopList.indexOf(lists)
                let indexs = lists.goods.findIndex(item => {
                    return item.goods_id == goodsId
                })
                let arrNew = this.shopList[index].goods[indexs]
                if (arrNew.num > 0) {
                    this.numSum--
                    arrNew.num--
                    this.shopMoneyNum -= (+arrNew.price)
                }
            }
            this.getShopCard()
        },
        // 减少
        shopOrderMinus(index) {
            if (this.orderList[index].num > 0) {
                this.orderList[index].num--
                this.numSum--
                // 计算金额
                this.shopMoneyNum -= (+this.orderList[index].price)
                if (this.orderList[index].num == 0) {
                    this.orderList.splice(index, 1)
                }
            }
        },
        //交易订单详情
        orderDetail() {
            this.isDetail = !this.isDetail
            if (this.isDetail) {
                this.isShade = true
                this.isShopList = false
            } else {
                this.isShade = false
            }
        },
        //关闭
        detailClose() {
            this.isDetail = false
            this.isShade = false
        },
        //返回
        paymentReturn() {
            this.isOilDetail = false
        },
        //选择支付方式
        selectPayment() {
            this.isOilDetail = true
            //异步加载滚动
            this.$nextTick(function () {
                const scrollSelect = new BScroll(this.$refs.wrappers, {
                    click: true
                })
            })
        },
        //打开支付详情
        paymentOpen() {
            this.isPayment = true
            this.isShade = true
            this.isDetail = false
            this.isShopList = false
            //判断加油卡是否可用
            this.oilMoney()
            //有油卡就用油卡支付
            this.$nextTick(function () {
                this.oilNewOn()
            })
        },
        //关闭支付详情
        paymentClose() {
            this.isPayment = false
            this.isShade = false
        },
        //打开关闭优惠券
        clickFavourable(state) {
            this.isFavourable = state
            this.isShade = state
            if (state) {
                this.$nextTick(function () {
                    const scrollFavourable = new BScroll(this.$refs.favourable, {
                        click: true
                    })
                })
            }
        },
        //打开关闭便利店
        clickShopShow(state) {
            this.isShopList = state
            this.isShade = state
            if (this.isShopsStart) {
                this.isShopsStart=false
                this.$nextTick(function () {
                    setTimeout(()=> {
                        this.shopScroll()
                    },500)
                })
            }
        },
        //初始化便利店滚动
        shopScroll() {
            this.classifyScroll = new BScroll(this.$refs.classify, {
                click: true
            })
            this.goodsScroll = new BScroll(this.$refs.goods, {
                probeType: 3,
                click: true
            })
            this.goodsScroll.on('scroll', (pos) => {
                this.goodsScrollY = Math.abs(Math.round(pos.y))
            })
            this.$nextTick(function () {
                this.getGoodsHeight()
            })
        },
        //初始化 取每个ul的高度，然后push放到一个数组里面
        getGoodsHeight() {
            this.listHeight = []
            let goodsEle = this.$refs.goods;
            let height = 0
            this.listHeight.push(height)
            this.goodsLists = goodsEle.getElementsByTagName('ul')
            for (let i = 0; i < this.goodsLists.length; i++) {
                height += this.goodsLists[i].clientHeight
                this.listHeight.push(height)
            }
        },
        //点击便利店左边列表
        clickShopList(index,event) {
            if (!event._constructed) {
                return;
            }
            let el = this.goodsLists[index]
            this.goodsScroll.scrollToElement(el, 300)
        },
        //点击积分抵现
        offset() {
            this.isOffset = !this.isOffset
            if (this.isOffset) {
                this.bpMonyeNum = this.integMoney
            } else {
                this.bpMonyeNum = 0
            }
        },
        //小球函数
        drop(el) {
            for (let i = 0; i < this.balls.length; i++) {
                let ball = this.balls[i]
                if (!ball.show) {
                    ball.show = true;
                    ball.el = el;
                    this.dropBalls.push(ball);
                    return;
                }
            }
        },
        //初始化小球
        afterDrop(el) {
            let ball = this.dropBalls.shift();
            if (ball) {
                ball.show = false;
                el.style.display = 'none';
            }
        },
        //小球动画开始
        beforeDrop(el) {
            let count = this.balls.length;
            while (count--) {
                let ball = this.balls[count]
                if (ball.show) {
                    let rect = ball.el.getBoundingClientRect()
                    let x = rect.left - this.NumX
                    let y = -(window.innerHeight - rect.top - this.NumY)
                    // console.log(y)
                    el.style.display = ''
                    el.style.transform = 'translateY(' + y + 'px)';
                    let inner = el.getElementsByClassName('inner-hook')[0];
                    inner.style.transform = 'translateX(' + x + 'px)';

                }

            }
        },
        //小球动画结束
        dropping(el, done) {
            let rf = el.offsetHeight;
            el.style.transform = 'translate3d(0,0,0)';
            let inner = el.getElementsByClassName('inner-hook')[0];
            inner.style.transform = 'translate3d(0,0,0)';
            el.addEventListener('transitionend', done);
        },
        //立即支付
        paymentBtn() {
            console.log('支付')
            this.isLoading=true
            setTimeout(() => {
                this.isLoading=false
                this.isSucceed=true
                setTimeout(() => {
                    this.isSucceed=false
                    window.location.href=""
                }, 2000);
            }, 2000);
        },
        //解决300ms延迟
        fastclick() {
            if ('addEventListener' in document) {
                document.addEventListener('DOMContentLoaded', function () {
                    FastClick.attach(document.body);
                }, false);
            }
        }

    },
})